﻿using System;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace AutoIE
{
    class ProcessorCompiler 
    {
        private CSharpCodeProvider _CSharpCodePrivoder = new CSharpCodeProvider();
        private CompilerParameters _CompilerParameters = new CompilerParameters();
        private CompilerResults _Clr;

        public ProcessorCompiler()
        {
            _CompilerParameters.ReferencedAssemblies.Add("System.dll");
            _CompilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            _CompilerParameters.GenerateInMemory = true;
        }
        public bool Compile(string code)
        {
            _Clr = _CSharpCodePrivoder.CompileAssemblyFromSource(_CompilerParameters, code);

            if (_Clr.Errors.HasErrors)
            {
                StringBuilder message = new StringBuilder();
                foreach (CompilerError err in _Clr.Errors)
                {
                    message.AppendFormat("({0}): error {1}: {2}", err.Line, err.ErrorNumber, err.ErrorText);
                }

                throw new Exception(message.ToString());
            }
            return true;
        }

        

        public BasicProcessor CreateInstance(string FullClassName)
        {
            if (_Clr == null)
                return null;
            Assembly objAssembly = _Clr.CompiledAssembly;
            BasicProcessor objClass = objAssembly.CreateInstance(FullClassName) as BasicProcessor;
            if (objClass == null)
            {
                throw new Exception("can not create instance of class " + FullClassName);
            }
            return objClass;
        }
    }
}
